import { createSSRApp } from 'vue'
import App from './App'
import { createPinia } from 'pinia'

// 路由白名单
const whiteList = ['/pages/auth/login', '/pages/auth/register'] // 不需要登录的页面

export function createApp() {
  const app = createSSRApp(App)
  const pinia = createPinia()
  app.use(pinia)
  
  // 全局路由守卫，在uni-app中使用插件方式
  const routeInterceptor = {
    install(app) {
      // 注意：uni-app的页面跳转不是Vue Router，需要使用uni.addInterceptor来实现
      uni.addInterceptor('navigateTo', {
        invoke(e) {
          return routeGuard(e.url)
        }
      })
      
      uni.addInterceptor('reLaunch', {
        invoke(e) {
          return routeGuard(e.url)
        }
      })
      
      uni.addInterceptor('redirectTo', {
        invoke(e) {
          return routeGuard(e.url)
        }
      })
      
      uni.addInterceptor('switchTab', {
        invoke(e) {
          return routeGuard(e.url)
        }
      })
    }
  }
  
  // 路由守卫函数
  function routeGuard(url) {
    const token = uni.getStorageSync('token')
    // 解析路径，去除参数部分
    const path = url.split('?')[0]
    
    if (token) {
      if (path === '/pages/auth/login') {
        uni.reLaunch({ url: '/pages/index/index' })
        return false
      }
      return true
    } else {
      if (whiteList.includes(path)) {
        return true
      } else {
        uni.reLaunch({ url: '/pages/auth/login' })
        return false
      }
    }
  }
  
  app.use(routeInterceptor)
  
  return {
    app
  }
} 